package com.zyx.mall.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zyx.mall.entity.Category;
import com.zyx.mall.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * <p>
 * 商品分类
 * </p>
 *
 * @author zyx
 * @since 2022-12-31
 */
@RestController
@RequestMapping("/api/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    //添加品类
    @PostMapping("/add")
    public Boolean addCategory(@RequestBody Category category) {
        categoryService.save(category);
        return true;
    }

    //品类列表(可带条件查询)
    @GetMapping("/pageList")
    public Page<Category> pageList(String name, String parentId, Integer pageSize, Integer currentPage) {
        Page<Category> page = new Page<>(currentPage, pageSize);

        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.like(name != null && name != "", "name", name)
                .eq(parentId != null && parentId != "", "parent_id", parentId)
                .orderByAsc("sort");
        categoryService.pageMaps(page, wrapper);
        return page;
    }

    //查询一级分类列表
    @GetMapping("/list")
    public List<Category> getList(String parentId) {
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.eq(parentId != null && parentId != "", "parent_id", parentId)
                .orderByAsc("sort");
        return categoryService.list(wrapper);
    }

    //更新品类信息
    @PutMapping("/update")
    public Boolean updateCategory(@RequestBody Category category) {
        return categoryService.updateById(category);
    }

    //删除品类信息
    @DeleteMapping("/del")
    public Boolean deleteCategory(String id) {
        return categoryService.removeById(id);
    }

    //通过id获取品类信息
    @GetMapping("/get")
    public Category getById(String id) {
        return categoryService.getById(id);
    }

    //查询二级分类列表
    @GetMapping("/getTree")
    public List<Category> getTree() {
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.ne("parent_id", 0);
        List<Category> list = categoryService.list(wrapper);
        return list;
    }

}

